package com.yanhui.utils.file;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;


public class _txtUtils {
	
	public static boolean searchKeyword(File file, String keyword) {  
        //参数校验  
        verifyParam(file, keyword);  
          
        //行读取  
        LineNumberReader lineReader = null;  
        try {  
            lineReader = new LineNumberReader(new FileReader(file));  
            String readLine = null;  
            while((readLine =lineReader.readLine()) != null){  
                //判断每一行中,出现关键词的次数  
                int index = 0;  
                int next = 0;  
                int times = 0;//出现的次数  
                //判断次数  
                while((index = readLine.indexOf(keyword,next)) != -1) {  
                    next = index + keyword.length();  
                    times++;  
                }  
                if(times > 0) {  
                    return true;
                	//System.out.println("第"+ lineReader.getLineNumber() +"行" + "出现 "+keyword+" 次数: "+times);  
                }  
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            //关闭流  
            close(lineReader);  
        }
		return false;  
    }  
	
	private static void verifyParam(File file, String keyword) {  
        //对参数进行校验证  
        if(file == null ){  
            throw new NullPointerException("the file is null");  
        }  
        if(keyword == null || keyword.trim().equals("")){  
            throw new NullPointerException("the keyword is null or \"\" ");  
        }  
          
        if(!file.exists()) {  
            throw new RuntimeException("the file is not exists");  
        }  
        //非目录  
        if(file.isDirectory()){  
            throw new RuntimeException("the file is a directory,not a file");  
        }  
          
        //可读取  
        if(!file.canRead()) {  
            throw new RuntimeException("the file can't read");  
        }  
    }  
	
	private static void close(Closeable able){  
        if(able != null){  
            try {  
                able.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
                able = null;  
            }  
        }  
    } 

	/**
	 * 重新写进文件中
	 * @param content 内容
	 * @param fileName 写入的文件
	 * @throws Exception
	 */
	public static void writeFileForContent(String content,String fileName) throws Exception{
		File file =new File(fileName);
		if(!file.exists()){
			file.createNewFile();
		}else{
			file.delete();
			file.createNewFile();
		}
		FileWriter fileWritter = new FileWriter(file.getPath(),true);
		fileWritter.write(content);
		fileWritter.flush();
		fileWritter.close();
	}
	
	public static String readTxtFile(String filePath){
		String result = "";
        try {
                String encoding="utf-8";
                File file=new File(filePath);
                if(file.isFile() && file.exists()){ 
                    InputStreamReader read = new InputStreamReader(
                    new FileInputStream(file),encoding);
                    BufferedReader bufferedReader = new BufferedReader(read);
                    String lineTxt = null;
                    while((lineTxt = bufferedReader.readLine()) != null){
                        result += lineTxt +"\r\n";
                    }
                    read.close();
        }else{
            System.out.println("找不到指定的文件");
        }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
        return result;
    }
	public static String readTxtFile2(String filePath){
		String result = "";
		try {
			String encoding="utf-8";
			File file=new File(filePath);
			if(file.isFile() && file.exists()){ 
				InputStreamReader read = new InputStreamReader(
						new FileInputStream(file),encoding);
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				while((lineTxt = bufferedReader.readLine()) != null){
					result += lineTxt +"<br>";
				}
				read.close();
			}else{
				System.out.println("找不到指定的文件");
			}
		} catch (Exception e) {
			System.out.println("读取文件内容出错");
			e.printStackTrace();
		}
		return result;
	}
	public static String readTxtFile2(String filePath, String encoding){
		String result = "";
		try {
			File file=new File(filePath);
			if(file.isFile() && file.exists()){ 
				InputStreamReader read = new InputStreamReader(
						new FileInputStream(file),encoding);
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				while((lineTxt = bufferedReader.readLine()) != null){
					result += lineTxt;
				}
				read.close();
			}else{
				System.out.println("找不到指定的文件");
			}
		} catch (Exception e) {
			System.out.println("读取文件内容出错");
			e.printStackTrace();
		}
		return result;
	}
	
	
	public static void writeTxtFile(String filePath, String content) throws Exception{
        File fileName = new File(filePath); 
        BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
        out.write(content);
        out.flush();
        out.close(); 
	}
	
	public static Integer readFileCount(String filePath) throws Exception {
		Integer count=0;
		File file = new File(filePath);
		FileInputStream fis = new FileInputStream(file);
		Scanner scanner = new Scanner(fis);
		while(scanner.hasNextLine()){
			scanner.nextLine();
			count++;
		}
		return count;
	}
	
	@SuppressWarnings("resource")
	public static Integer getLineByContext(String filePath, String context) throws IOException{
		/*File file = new File(filePath);
        BufferedReader reader = null;
        reader = new BufferedReader(new FileReader(file));
        String text = reader.readLine();
        Integer count=0;
        while (text != null) {
        	count++;
        	if(text.contains(context)){
        		return count;
        	}
        }*/
		Integer count=0;
		File file=new File(filePath);
        if(file.isFile() && file.exists()){ 
            InputStreamReader read = new InputStreamReader(
            new FileInputStream(file),"UTF-8");
            BufferedReader bufferedReader = new BufferedReader(read);
            String lineTxt = null;
            while((lineTxt = bufferedReader.readLine()) != null){
//                result += lineTxt +"\r\n";
            	count++;
            	if(lineTxt.contains(context)){
            		return count;
            	}
            }
            read.close();
        }
        return -1;
	}
	
	public static void deleteFileLine(String filePath, Integer line) throws Exception{
		File file = new File(filePath);
        BufferedReader reader = null;
        List<String> list = new ArrayList<String>();
        reader = new BufferedReader(new FileReader(file));
        String text = reader.readLine();
        Integer count=0;
        while (text != null) {
        	count++;
        	if(count != line){
        		list.add(text + "\r\n");
        	}
            text = reader.readLine();
        }
        reader.close();
        FileOutputStream outputStream = new FileOutputStream(file);
        for (String s : list) {
            outputStream.write(s.getBytes());
        }
        outputStream.close();
	}
	
	public static void deleteFileLines(String filePath, Integer[] line) throws Exception{
		for(int i = 0 ; i <line.length; i++){
			if(i>0){
				line[i] = line[i]-i;
			}
			deleteFileLine(filePath, line[i]);
		}
	}
	
	public static void addFileLine(String filePath, Integer line, String content) throws Exception{
		File file = new File(filePath);
        BufferedReader reader = null;
        List<String> list = new ArrayList<String>();
        reader = new BufferedReader(new FileReader(file));
        String text = reader.readLine();
        Integer count=0;
        while (text != null) {
        	count++;
        	if(count == line){
        		list.add(content + "\r\n");
        	}
        	list.add(text + "\r\n");
            text = reader.readLine();
        }
        reader.close();
        FileOutputStream outputStream = new FileOutputStream(file);
        for (String s : list) {
            outputStream.write(s.getBytes());
        }
        outputStream.close();
	}
	
	public static void addFileLines(String filePath, Integer[] line, String[] content) throws Exception{
		for(int i = 0 ; i <line.length; i++){
			addFileLine(filePath, line[i],content[i]);
		}
	}
	
//	public static void main(String[] args) throws Exception {
//		String filePath = "D:\\test.txt";
////		Integer res = readFileCount(filePath);
////		System.out.println(res);
//		Integer[] a = {2,4,6};
//		String[] b = {"dafudu2","5555的","666"};
////		deleteFileLines(filePath, a);
//		
////		addFileLine(filePath,2,"大幅度");
//		addFileLines(filePath,a,b);
//	}
	
	
	public static String getHtmlContent(String fileName) throws Exception{
		File file =new File(fileName);
		if(!file.exists()){
			return null;
		}
		StringBuffer sb = new StringBuffer();
		FileReader fr = new FileReader(file);  
		/** 
		 * 用Reader中的read方法读取字符。 
		 */
		int ch = 0;  
		while((ch = fr.read()) != -1){  
			sb.append((char)ch);
		}
		fr.close(); 
		return sb.toString();
	}
	public static void writeHtmlContent(String content,String fileName) throws Exception{
		File file =new File(fileName);
		if(!file.exists()){
			file.createNewFile();
		}else{
			file.delete();
			file.createNewFile();
		}
		FileWriter fileWritter = new FileWriter(file.getPath(),true);
		fileWritter.write(content);
		fileWritter.flush();
		fileWritter.close();
	}
	public static void addTxtContent(String fileName, String content) {   
        FileWriter writer = null;  
        try {     
            // 打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件     
            writer = new FileWriter(fileName, true);     
            writer.write(content);       
        } catch (IOException e) {     
            e.printStackTrace();     
        } finally {     
            try {     
                if(writer != null){  
                    writer.close();     
                }  
            } catch (IOException e) {     
                e.printStackTrace();     
            }     
        }   
    }     
	public static void main(String[] args) throws Exception {  //"\r\n"文件换行   <br>html文件换行
//		String b = "\r\n"+"大丰收";
//		b+="dfd";
//		String a = _txtUtil.getHtmlContent();
//		System.out.println(a);
//		a+= b;
//		writeHtmlContent(a);
		
//		int a = _txtUtils.getLineByContext("D:\\java_code\\YhAdminBase\\src\\main\\java\\com\\yanhui\\model\\User.java", "java.util.Date");
//		int b = _txtUtils.getLineByContext("D:\\java_code\\YhAdminBase\\src\\main\\java\\com\\yanhui\\model\\User.java", "private Date");
//		_txtUtils.deleteFileLine("D:\\java_code\\YhAdminBase\\src\\main\\java\\com\\yanhui\\model\\User.java", 8);
//		System.out.println(b);
		File file = new File("D:\\java_code\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp2\\wtpwebapps\\YhBase2\\yhfile\\code\\e843073b78714da5bc7d99eea3c95d1ce877e.txt");
		boolean a = searchKeyword(file, "json23");
		System.out.println(a);
	}
	
	
	public static boolean checkTxtEsist(String txtFileName, String keyword) {
		try {
			String content = _txtUtils.getHtmlContent(txtFileName);
			if(content.contains(keyword)){
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public static String getBigDataTxt(String filePath, int len) throws Exception{
		String result = "";
		File file=new File(filePath);
		InputStreamReader read = new InputStreamReader(
				new FileInputStream(file),"UTF-8");
		BufferedReader bufferedReader = new BufferedReader(read);
		String lineTxt = null;
		while((lineTxt = bufferedReader.readLine()) != null){
			//1、接受数据
			String line = lineTxt;
			//2、数据切片
			String[] fields = line.split(",");
			if(fields.length >= len){
				//3、拿到关键字段
				String sexStr = fields[len];
				//4、数据输出到
				if(sexStr!=null && !"".equals(sexStr.trim()) && !"性别".equals(sexStr)){
					result += sexStr+","; 
				}
			}
		}
		read.close();
		return result;
	}
	
	//len 性别,地区
	public static String getBigDataTxt(String filePath, int[] len) throws Exception{
		String result = "";
		File file=new File(filePath);
		InputStreamReader read = new InputStreamReader(
				new FileInputStream(file),"UTF-8");
		BufferedReader bufferedReader = new BufferedReader(read);
		String lineTxt = null;
		while((lineTxt = bufferedReader.readLine()) != null){
			//1、接受数据
			String line = lineTxt;
			//2、数据切片
			String[] fields = line.split(",");
			if(fields.length >= len[0]){
				//3、拿到关键字段
				String sexStr = fields[len[0]];
				String areaStr = fields[len[1]];
				//4、数据输出到
				if(sexStr!=null && !"".equals(sexStr.trim()) && !"性别".equals(sexStr)){
					result += sexStr+"-"+areaStr+","; 
				}
			}
		}
		read.close();
		return result;
	}
	
}
